#include "pdMonitorService.h"
#include "PD_UFP.h"
#include "PD_UFP_Log.h"
#include "env.h"
#include "debug.h"
#include "xmath.h"
#include "env.h"
#include "stdio.h"
#define BOOT_DELAY 500
#define BOOT_DELAY_COUNT(x) (x / PD_MONITOR_SERVICE_DURATION)
// 在PD2.0条件下，最高请求12V输入，以便更高的输出电流
#define PD2_0_VOLT PD_POWER_OPTION_MAX_12V
// 在PD3.0条件下，最高支持13.8V原始电压输入，以3.0A进行输出，以便获得最大电流
#define PD3_0_VOLT PPS_V(13.8)
#define PD3_0_CURR PPS_A(3.0)
static unsigned int bootDelay = 0;
void sPdMonitorInit(void)
{
    PD_UFP_ErrTable ret;
    if (env.error == E_CRITICAL)
    {
        return;
    }

    ret = PD_UFPInit(PD3_0_VOLT, PD3_0_CURR, PD_POWER_OPTION_MAX_POWER);
    if (ret != E_PD_UFP_OK)
    {
        PRINTF("[CRITICAL]: PD UFP Init failed!\n");
        sprintf(env.message, "PD CHIP ERR!");
        env.error = E_CRITICAL;
    }
}
static unsigned char doOnce = 0;

void sPDMonitorLoop(void)
{
    float current = 0.0;
    float voltage = 0.0;

    if (env.chargerMode != E_CHARGE_MODE_PD)
    {
        return;
    }
    if(env.error == E_CRITICAL)
    {
        return;
    }
    if (bootDelay < BOOT_DELAY_COUNT(BOOT_DELAY))
    {
        bootDelay++;
        return;
    }
    run();
    if (is_power_ready())
    {
        if (doOnce == 0)
        {
            doOnce = 1;
            current = get_current();
            voltage = get_voltage();

            if (xfabs(voltage - 5.0) < 0.0001 || xfabs(current - 1.0) < 0.0001)
            {
                PRINTF("[PD]: not support!\n");
                env.sourceCapCurrent = current;
                env.sourceCapVoltage = voltage;
                env.chargerMode = E_CHARGE_MODE_QC;
            }
            else
            {
                env.ready = E_SUPPLY_READY;
                env.sourceCapCurrent = current;
                env.sourceCapVoltage = voltage;
            }
        }
        pu_print_status();
    }
}

void sPdMonitorRegisterOnDeviceDetected(pdMonitorCallback callback)
{
    // TODO:
}
